package ${package}.${rootArtifactId}.common.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * RequestContext 工具
 *
 * @author weidong.lin
 * @date 2021/7/15 11:22
 */
public class RequestContextUtil {
    private static ThreadLocal<HttpSession> localSession = new ThreadLocal();
    private static ThreadLocal<HttpServletRequest> localRequest = new ThreadLocal();

    public static HttpSession getSession() {
        return getSession(true);
    }

    public static HttpSession getSession(boolean create) {
        HttpSession session = (HttpSession) localSession.get();
        if (session != null && ValidatorUtil.isEmpty(session.getId())) {
            return null;
        } else {
            if (session == null) {
                HttpServletRequest request = (HttpServletRequest) localRequest.get();
                if (request != null) {
                    session = request.getSession(create);
                }
            }

            return session;
        }
    }
}
